<template>
  <app-page :login="false" :cusStyle="{ position: 'relative', zIndex: 1 }">
    <view class="head-box" :style="{ height: `${safeTopHeight + navHeight}px` }">
      <mxp-navbar :placeholder="true" :showLine="false" titleWidth="0px" :showBack="false" title="">
        <!-- #ifndef MP-TOUTIAO -->
        <template #left>
          <view style="display: flex; flex-direction: row; place-items: center center">
            <image src="@/static/images/logo2.svg" style="width: 30px; height: 30px"></image>
            <text style="font-size: 12px; color: #666666">{{ appInfo?.name || '袋鼠短剧' }}</text>
          </view>
        </template>
        <!-- #endif -->
        <template #right>
          <mxp-search
            background="#ffffff"
            borderColor="#eeeeee"
            height="30px"
            placeholder="请输入"
            placeholderColor="#998F4B"
            color="#998F4B"
            :cusStyle="{ margin: '15px 0', opacity: 0.6 }"
            :disabled="true"
            @click="onSearch"
          ></mxp-search>
        </template>
      </mxp-navbar>
    </view>
    <!-- 占位 -->
    <view :style="{ height: `${safeTopHeight + navHeight}px` }"></view>
    <mxp-refresh-page ref="mxpRefreshPageRef" :queryData="queryData" :emptyHeight="`${sys.windowHeight - (safeTopHeight + navHeight)}px`">
      <view style="padding-left: 30rpx">
        <swiper v-if="swiperList.length > 0" class="swiper-public" :indicatorDots="true" :autoplay="true" :circular="true" @change="swiperChange">
          <swiper-item v-for="(item, index) in swiperList" :key="item.bannerId" class="swiper-public" @click="swiperClick(index)">
            <image :src="item.bannerUrl" mode="scaleToFill" class="swiper-public"></image>
          </swiper-item>
        </swiper>
      </view>
      <view class="middle-action-box">
        <view class="action-list">
          <view class="action" @click="openPaidRankClick">
            <view class="ico-box"><image class="ico" src="/static/images/tab-bar/ico_heat_white.svg"></image></view>
            <view class="action-text-bg"><text class="text">热力榜</text></view>
          </view>
          <view class="action" @click="openBingeWatchRankClick">
            <view class="ico-box"><image class="ico" src="/static/images/video/ico_fav.svg"></image></view>
            <view class="action-text-bg"><text class="text">追剧榜</text></view>
          </view>
          <view class="action" @click="openSignInClick">
            <view class="ico-box"><image class="ico" src="/static/images/tab-bar/ico_sign_in1.svg"></image></view>
            <view class="action-text-bg"><text class="text">签到</text></view>
          </view>
          <view class="action" @click="openDiscountCouponListClick">
            <view class="ico-box"><image class="ico" src="/static/images/tab-bar/ico_discount_coupon.svg"></image></view>
            <view class="action-text-bg"><text class="text">券码包</text></view>
          </view>
        </view>
      </view>

      <view>
        <!-- 最近播放 -->
        <view v-if="viewRecord" class="handpick-vessel" :style="{ '--handpick-background': defThemeColor.fill }">
          <view class="view-record" style="margin-top: 10px" @click="openVideoDetails(viewRecord)">
            <view class="tag-box">
              <text style="font-size: 12px; color: #ffffff">最近播放</text>
            </view>
            <view style="margin-right: 30rpx">
              <mxp-image width="210rpx" height="336rpx" errorSize="22px" borderRadius="10px" :src="viewRecord.dramaCover"></mxp-image>
            </view>
            <view style="flex: 1; width: 450rpx; padding: 10px 0">
              <view class="record-title-box">
                <text class="record-title" :style="{ color: defThemeColor.text }">{{ viewRecord.dramaTitle }}</text>
              </view>
              <view class="record-head-box">
                <view>
                  <mxp-tags
                    v-for="(category, index2) in viewRecord.categoryList"
                    :key="index2"
                    :text="category"
                    size="min"
                    :cusStyle="{ marginRight: '8px' }"
                    :plainBorder="false"
                    :plain="true"
                    :closable="false"
                  ></mxp-tags>
                </view>
                <view class="butt-box">
                  <image src="/static/public/ico_play_white.svg" style="width: 12px; height: 12px" mode="scaleToFill"></image>
                  <text style="font-size: 12px; line-height: 12px; color: #ffffff">立即观看</text>
                </view>
              </view>
              <view class="record-info-box">
                <text class="intro record-info" :style="{ color: defThemeColor.text3 }">简介: {{ viewRecord.dramaDesp || '' }}</text>
              </view>
            </view>
          </view>
        </view>
        <!-- 达人精选 -->
        <template v-if="handpickList.length > 0">
          <view class="handpick-vessel" :style="{ '--handpick-background': defThemeColor.fill }">
            <mxp-tag-title title="达人精选" fontSize="16px">
              <template #right>
                <mxp-button
                  leftIcon="/static/images/tab-bar/ico_refresh.svg"
                  text="换一批"
                  size="middle"
                  :loading="goodLoadingState"
                  :disabled="goodLoadingState"
                  color="#B8AB80"
                  :isTextButton="true"
                  @click="refreshGoodDrama"
                ></mxp-button>
              </template>
            </mxp-tag-title>
            <view v-if="handpickObj" class="view-record" @click="openVideoDetails(handpickObj)">
              <view style="margin-right: 30rpx">
                <mxp-image width="210rpx" height="336rpx" errorSize="22px" borderRadius="10px" :src="handpickObj.dramaCover"></mxp-image>
              </view>
              <view style="flex: 1; width: 450rpx; padding: 10px 0">
                <view class="record-title-box">
                  <text class="record-title" :style="{ color: defThemeColor.text }">{{ handpickObj.dramaTitle }}</text>
                </view>
                <view class="record-head-box">
                  <view>
                    <mxp-tags
                      v-for="(category, index2) in handpickObj.categoryList"
                      :key="index2"
                      :text="category"
                      :cusStyle="{ marginRight: '8px' }"
                      size="min"
                      :plainBorder="false"
                      :plain="true"
                      :closable="false"
                    ></mxp-tags>
                  </view>
                  <view class="butt-box">
                    <image src="/static/public/ico_play_white.svg" style="width: 12px; height: 12px" mode="scaleToFill"></image>
                    <text style="font-size: 12px; line-height: 12px; color: #ffffff">立即观看</text>
                  </view>
                </view>
                <view class="record-info-box">
                  <text class="intro record-info" :style="{ color: defThemeColor.text3 }">简介: {{ handpickObj.dramaDesp || '' }}</text>
                </view>
              </view>
            </view>
            <view class="handpick-list" style="margin-top: 15px">
              <view v-for="(item, index) in handpickList" :key="index" class="handpick-item" @click="openVideoDetails(item)">
                <view style="padding-bottom: 8px">
                  <mxp-image width="210rpx" height="336rpx" errorSize="80rpx" borderRadius="10px" :src="item.dramaCover"></mxp-image>
                </view>
                <view class="info-box">
                  <text class="title" :style="{ color: defThemeColor.text }">{{ item.dramaTitle }}</text>
                  <text class="info" :style="{ color: defThemeColor.text3 }">共{{ item.seqNum }}集</text>
                </view>
              </view>
            </view>
          </view>
        </template>
        <!-- 热门推荐 -->
        <template v-if="hotList.length > 0">
          <view class="handpick-vessel" :style="{ '--handpick-background': defThemeColor.fill }">
            <mxp-tag-title title="热门推荐" :bold="true" fontSize="24px">
              <template #right>
                <mxp-button
                  leftIcon="/static/images/tab-bar/ico_refresh.svg"
                  text="换一批"
                  size="middle"
                  color="#B8AB80"
                  :isTextButton="true"
                  :loading="hotLoadingState"
                  :disabled="hotLoadingState"
                  @click="refreshHotDrama"
                ></mxp-button>
              </template>
            </mxp-tag-title>
            <view v-for="item in hotList" :key="item.dramaId" class="view-record" style="margin-top: 15px" @click="openVideoDetails(item)">
              <view style="margin-right: 30rpx">
                <mxp-image width="210rpx" height="336rpx" errorSize="22px" borderRadius="10px" :src="item.dramaCover"></mxp-image>
              </view>
              <view style="flex: 1; width: 450rpx; padding: 10px 0">
                <view style="display: flex; flex-direction: row; align-items: center; justify-content: center; width: 100%">
                  <view class="record-title-box">
                    <text class="record-title" :style="{ color: defThemeColor.text }">{{ item.dramaTitle }}</text>
                  </view>
                  <view style="display: flex; flex-direction: row; align-items: center; justify-content: center">
                    <image src="/static/images/tab-bar/ico_heat_red.svg" style="width: 12px; height: 12px" mode="scaleToFill"></image>
                    <text style="font-size: 12px; line-height: 12px; color: #ff0000">{{ item.hotNum }}</text>
                  </view>
                </view>
                <view class="record-head-box">
                  <view>
                    <mxp-tags
                      v-for="(category, index2) in item.categoryList"
                      :key="index2"
                      :text="category"
                      size="min"
                      :cusStyle="{ marginRight: '8px' }"
                      :plainBorder="false"
                      :plain="true"
                      :closable="false"
                    ></mxp-tags>
                  </view>
                  <view class="butt-box">
                    <image src="/static/public/ico_play_white.svg" style="width: 12px; height: 12px" mode="scaleToFill"></image>
                    <text style="font-size: 12px; line-height: 12px; color: #ffffff">立即观看</text>
                  </view>
                </view>
                <view class="record-info-box">
                  <text class="intro record-info" :style="{ color: defThemeColor.text3 }">简介: {{ item.dramaDesp || '' }}</text>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
      <view style="height: 40px"></view>
    </mxp-refresh-page>
  </app-page>
</template>

<script setup lang="ts">
  import { type Ref, computed, ref, watch } from 'vue';
  import { onPullDownRefresh, onShow } from '@dcloudio/uni-app';
  import type { SwiperOnChangeEvent } from 'mxp-uni-types';
  import AppPage from '@/components/app-page/app-page.vue';
  import MxpButton from '@/mxp-ui/mxp-button/mxp-button.vue';
  import MxpNavbar from '@/mxp-ui/mxp-navbar/mxp-navbar.vue';
  import MxpTags from '@/mxp-ui/mxp-tags/mxp-tags.vue';
  import MxpImage from '@/mxp-ui/mxp-image/mxp-image.vue';
  import MxpTagTitle from '@/mxp-ui/mxp-tag-title/mxp-tag-title.vue';
  import {
    type DramaViewRecord,
    type HandpickDrama,
    type HomeBanner,
    type HotDrama,
    getGoodDramaListAxios,
    getHomeBannerAxios,
    getHotDramaListAxios,
    getLastViewRecordByUserIdAxios,
  } from '@/api/drama';
  import { useAppStore } from '@/pinia/app';
  import { openPlayletPage } from '@/utils/page/rest';
  import { defThemeColor } from '@/mxp-ui/mxp-tool/theme/theme';
  import { autoLogin } from '@/utils/page/user';
  import MxpRefreshPage, { type Ins } from '@/mxp-ui/mxp-refresh-page/mxp-refresh-page.vue';
  import { useRefresh } from '@/mxp-ui/mxp-tool/hooks/useHooksRefresh.ts';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import MxpSearch from '@/mxp-ui/mxp-search/mxp-search.vue';
  import { getAppInfo } from '@/config/mp-config';
  import { getHeaderHeight } from '@/mxp-ui/mxp-tool/utils/dom';

  const { mxpRefreshPageRef } = useRefresh(onPullDownRefresh);
  const sys = mxpGetSysInfoStore().getSysInfo();
  console.log('sys=========>', sys);
  const appInfo = getAppInfo();
  /** 轮播图当前 index */
  const swiperIndex = ref(0);
  /** 轮播列表 */
  const swiperList: Ref<HomeBanner[]> = ref([]);
  /** 最近观看 */
  const viewRecord: Ref<DramaViewRecord | null> = ref(null);
  /** 达人精选 */
  const handpickObj: Ref<HandpickDrama | null> = ref(null);
  /** 达人精选 */
  const handpickList: Ref<HandpickDrama[]> = ref([]);
  /** 热门推荐 */
  const hotList: Ref<HotDrama[]> = ref([]);
  /** 登录状态 */
  const loginState = computed(() => useAppStore().loginState);
  /** 顶部安全区高度 */
  const safeTopHeight = computed(() => sys.value.statusBarHeight || 0);
  const goodLoadingState = ref(false);
  const hotLoadingState = ref(false);
  const currPage = { good: 1, hot: 1 };

  /** 高度 */
  const navHeight = computed(() => getHeaderHeight(sys.value.statusBarHeight));

  let init = false; // 用于仅在返回时才刷新

  watch(
    () => loginState.value,
    (state) => {
      init && state && mxpRefreshPageRef.value?.initLoadRefresh();
    }
  );

  onShow(() => {
    init && loginState.value && getLastViewRecord();
  });

  /** 加载数据 */
  async function queryData(ins: Ins) {
    if (!mxpRefreshPageRef.value) {
      mxpRefreshPageRef.value = ins as InstanceType<typeof MxpRefreshPage>;
    }
    try {
      init = false;
      try {
        // 如果未登录先静默登录
        !loginState.value && (await autoLogin());
      } catch (error) {}
      currPage.hot = 1;
      currPage.good = 1;
      const list: unknown[] = [getHomeBanner(), refreshGoodDrama(), refreshHotDrama()];
      loginState.value && list.push(getLastViewRecord());
      await Promise.all(list);
      init = true;
      ins.setSuccess();
    } catch (error) {
      init = true;
      ins?.setEmpty('fail_load', error.msg || '获取数据失败，BD001');
    }
  }

  /**
   * 得到轮播图
   */
  async function getHomeBanner() {
    try {
      const res = await getHomeBannerAxios(1);
      swiperList.value = res.data.records;
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject(error);
    }
  }

  /**
   * 得到最后一条观看记录
   */
  async function getLastViewRecord() {
    try {
      const res = await getLastViewRecordByUserIdAxios();
      viewRecord.value = res.data;
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject(error);
    }
  }

  /**
   * 刷新热门精选
   */
  async function refreshHotDrama() {
    try {
      hotLoadingState.value = true;
      const res = await getHotDramaListAxios(currPage.hot, 3);
      hotList.value = res!.data.records;
      const totalPage = Math.ceil(res.data.total / res.data.size);
      currPage.hot = currPage.hot + 1 > totalPage ? 1 : currPage.hot + 1; // 加载成功后加 1
      hotLoadingState.value = false;
      return Promise.resolve(true);
    } catch (error) {
      hotLoadingState.value = false;
      return Promise.reject(error);
    }
  }

  /**
   * 刷新达人推荐
   */
  async function refreshGoodDrama() {
    try {
      goodLoadingState.value = true;
      const res = await getGoodDramaListAxios(currPage.good, 4);
      handpickObj.value = res!.data.records[0] || null;
      handpickList.value = res!.data.records.splice(1);
      const totalPage = Math.ceil(res.data.total / res.data.size);
      currPage.good = currPage.good + 1 > totalPage ? 1 : currPage.good + 1; // 加载成功后加 1
      goodLoadingState.value = false;
      return Promise.resolve(true);
    } catch (error) {
      goodLoadingState.value = false;
      return Promise.reject(error);
    }
  }

  /** 监听轮播切换 */
  function swiperChange(event: SwiperOnChangeEvent) {
    swiperIndex.value = event.detail?.current || 0;
  }

  /** 点击swiper的某一个 */
  function swiperClick(index: number) {
    const swiper = swiperList.value[index];
    if (index >= 0 && swiper) {
      if (swiper.jumpType === 1 && swiper.businessId) {
        openVideoDetails({ ...swiper, dramaId: swiper.businessId });
      } else if (swiper.jumpType === 2 && swiper.bannerLink) {
        uni.navigateTo({
          url: `/pages/rest/web-view-page/web-view-page?url=${encodeURIComponent(swiper.bannerLink)}`,
        });
      }
    }
  }
  /** 打开视频详情 */
  function openVideoDetails(item: DramaViewRecord | HandpickDrama | HotDrama | (HomeBanner & { dramaId: number })) {
    openPlayletPage(item);
  }
  /** 付费最多 */
  function openPaidRankClick() {
    uni.navigateTo({ url: '/pages/drama/paid-rank/paid-rank' });
  }

  /** 追剧最多 */
  function openBingeWatchRankClick() {
    uni.navigateTo({ url: '/pages/drama/binge-watch-rank/binge-watch-rank' });
  }

  /** 搜索 */
  function onSearch() {
    uni.navigateTo({ url: `/pages/drama/drama-search/drama-search` });
  }

  /** 打开签到页面 */
  function openSignInClick() {
    if (loginState.value) {
      uni.navigateTo({ url: '/pages/personal/sign-in/sign-in' });
    } else {
      uni.navigateTo({ url: '/pages/account/login/login' });
    }
  }

  /** 打开券码包页面 */
  function openDiscountCouponListClick() {
    if (loginState.value) {
      uni.navigateTo({ url: '/pages/rest/discount-coupon-list/discount-coupon-list' });
    } else {
      uni.navigateTo({ url: '/pages/account/login/login' });
    }
  }
</script>

<style lang="scss" scoped>
  .head-box {
    position: fixed;
    top: 0;
    z-index: 222;
    width: 100vw;
    height: 84px;
    background: #f8f8f8;
  }

  .page-bg-img-box {
    position: absolute;
    top: 180rpx;
    left: 00rpx;
    z-index: 0;
    width: 100vw;
    height: 70vh;
    background: linear-gradient(180deg, #d876f0, #9df1ee 200px, #f8f8f8 300px, #f8f8f8);

    .page-bg-img {
      width: 750rpx;
      height: 400rpx;
    }
  }

  .swiper-public {
    width: 690rpx;
    height: 320rpx;
    overflow: hidden;
    border-radius: 10rpx;
  }

  .view-record {
    position: relative;
    box-sizing: border-box;
    display: flex;
    width: 690rpx;
    margin-top: 0;
    vertical-align: top;
    border-radius: 10px;

    .record-head-box {
      box-sizing: border-box;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      width: 450rpx;
      padding: 10px 0;
    }

    .record-title-box {
      flex: 1;
      overflow: hidden;

      .record-title {
        display: -webkit-box;
        overflow: hidden;
        font-size: 16px;
        font-weight: bold;
        line-height: 18px;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        line-clamp: 1;
      }
    }

    .record-info-box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      width: 100%;
      margin-top: 6px;

      .record-info {
        font-size: 12px;
        text-align: justify;
      }

      .intro {
        display: -webkit-box;
        overflow: hidden;
        word-break: break-all;
        -webkit-line-clamp: 4;
        line-clamp: 4;
        -webkit-box-orient: vertical;
      }
    }

    .tag-box {
      position: absolute;
      top: -15px;
      left: 0;
      z-index: 2;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 4px 12px;
      margin-top: 6px;
      background: #f23009;
      border-radius: 20px;
    }

    .butt-box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 70px;
      padding: 8px 6px;
      background: linear-gradient(129deg, #fdbf00 0%, #fd6e00 100%);
      border-radius: 20px;
    }
  }

  .handpick-vessel {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30rpx;
    padding-bottom: 30rpx;
    margin-top: 10px;
    background: var(--handpick-background);

    .handpick-list {
      box-sizing: border-box;
      display: flex;
      flex-flow: row wrap;
      justify-content: space-between;
      width: 690rpx;

      .handpick-item {
        display: flex;
        flex-direction: column;
        width: 210rpx;

        .info-box {
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          width: 210rpx;
          overflow: hidden;

          .title {
            overflow: hidden;
            font-size: 14px;
            font-weight: bold;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .info {
            font-size: 12px;
          }
        }
      }
    }
  }

  .handpick-vessel:first-child {
    background: linear-gradient(to bottom, rgba(255, 255, 255, 0), #ffffff);
  }

  .middle-action-box {
    box-sizing: border-box;
    width: 100vw;
    padding-top: 20px;
    padding-bottom: 10px;

    .action-list {
      box-sizing: border-box;
      display: flex;
      flex-flow: row nowrap;
      place-content: center space-between;
      align-items: center;
      width: 100%;
      min-width: 0;
      padding: 0 15px;

      .action {
        display: flex;
        flex-flow: column nowrap;
        place-content: center center;
        align-items: center;

        .ico-box {
          z-index: 2;
          display: flex;
          flex-flow: column nowrap;
          place-content: center center;
          align-items: center;
          width: 30px;
          height: 30px;
          border-radius: 12px;

          .ico {
            width: 18px;
            height: 18px;
          }
        }

        &:nth-child(1) .ico-box {
          background: linear-gradient(to bottom, #4bc0ff, #78d0fb);
        }

        &:nth-child(2) .ico-box {
          background: linear-gradient(to bottom, #ff8744, #ffab74);
        }

        &:nth-child(3) .ico-box {
          background: linear-gradient(to bottom, #ff625a, #ff8477);
        }

        &:nth-child(4) .ico-box {
          background: linear-gradient(to bottom, #ac6dfb, #ba8bfc);
        }

        .action-text-bg {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 144rpx;
          height: 40px;
          padding-top: 10px;
          margin-top: -20px;
          background: rgba(255, 255, 255, 0.4);
          border-radius: 40px 10px 10px 12px;

          .text {
            display: block;
            margin-top: 5px;
            font-size: 13px;
            font-weight: bold;
            font-stretch: normal;
            text-align: center;
          }
        }
      }
    }
  }
</style>
